#!/bin/bash
# 微服务系统启动脚本

echo "开始启动充电宝租赁系统微服务..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查Java环境
check_java() {
    if ! command -v java &> /dev/null; then
        log_error "Java未安装或未配置环境变量"
        exit 1
    fi
    
    java_version=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')
    log_info "检测到Java版本: $java_version"
}

# 检查Maven环境
check_maven() {
    if ! command -v mvn &> /dev/null; then
        log_error "Maven未安装或未配置环境变量"
        exit 1
    fi
    
    mvn_version=$(mvn -version | head -n 1)
    log_info "检测到Maven: $mvn_version"
}

# 检查数据库连接
check_database() {
    log_info "检查数据库连接..."
    
    if ! command -v mysql &> /dev/null; then
        log_error "MySQL客户端未安装"
        exit 1
    fi
    
    # 这里可以添加实际的数据库连接检查
    log_info "数据库连接正常"
}

# 检查Redis连接
check_redis() {
    log_info "检查Redis连接..."
    
    if ! command -v redis-cli &> /dev/null; then
        log_error "Redis客户端未安装"
        exit 1
    fi
    
    if ! redis-cli ping > /dev/null 2>&1; then
        log_error "Redis连接失败，请确保Redis已启动"
        exit 1
    fi
    
    log_info "Redis连接正常"
}

# 构建项目
build_project() {
    local project_name=$1
    local project_path=$2
    
    log_info "构建项目: $project_name"
    
    cd "$project_path" || exit 1
    
    if mvn clean package -DskipTests > /dev/null 2>&1; then
        log_info "✓ $project_name 构建成功"
    else
        log_error "✗ $project_name 构建失败"
        exit 1
    fi
    
    cd - > /dev/null || exit 1
}

# 启动服务
start_service() {
    local service_name=$1
    local jar_path=$2
    local port=$3
    
    log_info "启动服务: $service_name (端口: $port)"
    
    # 检查端口是否被占用
    if lsof -i:$port > /dev/null 2>&1; then
        log_warn "端口 $port 已被占用，尝试停止现有进程..."
        kill -9 $(lsof -ti:$port) 2>/dev/null || true
        sleep 2
    fi
    
    # 启动服务
    nohup java -jar "$jar_path" > "logs/${service_name}.log" 2>&1 &
    local pid=$!
    
    # 等待服务启动
    sleep 10
    
    # 检查服务是否启动成功
    if ps -p $pid > /dev/null 2>&1; then
        log_info "✓ $service_name 启动成功 (PID: $pid)"
        echo "$pid" > "pids/${service_name}.pid"
    else
        log_error "✗ $service_name 启动失败"
        exit 1
    fi
}

# 检查服务健康状态
check_health() {
    local service_name=$1
    local health_url=$2
    
    log_info "检查 $service_name 健康状态..."
    
    for i in {1..30}; do
        if curl -s "$health_url" > /dev/null 2>&1; then
            log_info "✓ $service_name 健康检查通过"
            return 0
        fi
        sleep 2
    done
    
    log_error "✗ $service_name 健康检查失败"
    return 1
}

# 创建必要目录
create_directories() {
    mkdir -p logs
    mkdir -p pids
    log_info "创建日志和PID目录"
}

# 主流程
main() {
    log_info "开始微服务系统启动流程"
    
    # 环境检查
    check_java
    check_maven
    check_database
    check_redis
    
    # 创建目录
    create_directories
    
    # 构建所有项目（如果需要）
    if [ "$1" = "--build" ]; then
        log_info "开始构建所有项目..."
        build_project "用户中心" "./user-center"
        build_project "支付中心" "./payment-center" 
        build_project "订单中心" "./order-center"
        build_project "设备中心" "./device-center"
        build_project "财务中心" "./finance-center"
        build_project "运营后台" "./admin-system"
        build_project "API网关" "./api-gateway"
    fi
    
    # 按依赖顺序启动服务
    log_info "开始启动服务..."
    
    # 1. 启动用户中心
    start_service "user-center" "./user-center/target/user-center-1.0.0-SNAPSHOT.jar" "8001"
    check_health "user-center" "http://localhost:8001/user-center/actuator/health"
    
    # 2. 启动支付中心
    start_service "payment-center" "./payment-center/target/payment-center-1.0.0-SNAPSHOT.jar" "8002"
    check_health "payment-center" "http://localhost:8002/payment-center/actuator/health"
    
    # 3. 启动设备中心
    start_service "device-center" "./device-center/target/device-center-1.0.0-SNAPSHOT.jar" "8004"
    check_health "device-center" "http://localhost:8004/device-center/actuator/health"
    
    # 4. 启动财务中心
    start_service "finance-center" "./finance-center/target/finance-center-1.0.0-SNAPSHOT.jar" "8005"
    check_health "finance-center" "http://localhost:8005/finance-center/actuator/health"
    
    # 5. 启动订单中心
    start_service "order-center" "./order-center/target/order-center-1.0.0-SNAPSHOT.jar" "8003"
    check_health "order-center" "http://localhost:8003/order-center/actuator/health"
    
    # 6. 启动运营后台
    start_service "admin-system" "./admin-system/target/admin-system-1.0.0-SNAPSHOT.jar" "8006"
    check_health "admin-system" "http://localhost:8006/admin-system/actuator/health"
    
    # 7. 启动API网关
    start_service "api-gateway" "./api-gateway/target/api-gateway-1.0.0-SNAPSHOT.jar" "8000"
    check_health "api-gateway" "http://localhost:8000/actuator/health"
    
    log_info "所有服务启动完成！"
    log_info "API网关地址: http://localhost:8000"
    log_info "查看服务状态: ./scripts/status.sh"
    log_info "停止所有服务: ./scripts/stop.sh"
}

# 显示帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  --build    构建所有项目后启动"
    echo "  --help     显示帮助信息"
    echo ""
    echo "示例:"
    echo "  $0           # 直接启动服务"
    echo "  $0 --build   # 构建后启动服务"
}

# 参数处理
case "$1" in
    --help)
        show_help
        exit 0
        ;;
    --build|"")
        main "$1"
        ;;
    *)
        log_error "未知参数: $1"
        show_help
        exit 1
        ;;
esac